package com.itheima.interceptor;

import com.itheima.utils.CurrentHolder;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
//@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        //获取url路径
        String url=  request.getRequestURI().toString();//     /login
        //如果是login请求，则放行
        if(url.contains("login"))
        {
            log.info("login请求放行");
            return true;
        }
        //其他获取请求头的token
        String token= request.getHeader("token");
        //判断token是否存在 不存在返回401状态码
        if(token==null||token.equals(""))
        {
            log.error("token不存在");
            response.setStatus(401);
            return false;
        }
        //存在判断token是否正确和是否过期
        try {
            Claims claims = JwtUtils.parseToken(token);
         Integer empId =   Integer.valueOf(claims.get("id").toString());
         CurrentHolder.setCurrentId(empId);
            log.info("当前用户id为："+empId);
        } catch (Exception e) {
            log.error("token验证失败");
            response.setStatus(401);
            return false;
        }
        //如果正确，则放行
        log.info("token验证成功");
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        CurrentHolder.remove();
    }
}
